package com.fancy.user.interceptor;

import com.fancy.user.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * JWT认证拦截器
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthInterceptor implements HandlerInterceptor {

    private final JwtUtils jwtUtils;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求路径
        String requestURI = request.getRequestURI();

        // 排除不需要认证的路径
        if (isExcludedPath(requestURI)) {
            return true;
        }

        // 获取Authorization header
        String authHeader = request.getHeader("Authorization");

        if (!StringUtils.hasText(authHeader) || !authHeader.startsWith("Bearer ")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"未提供有效的认证信息\"}");
            return false;
        }

        // 提取token
        String token = authHeader.substring(7);

        try {
            // 验证token
            String username = jwtUtils.getUsernameFromToken(token);
            if (!jwtUtils.validateToken(token, username)) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write("{\"code\":401,\"message\":\"认证信息已过期或无效\"}");
                return false;
            }

            // 将用户信息设置到请求属性中
            String userId = jwtUtils.getUserIdFromToken(token);
            String role = jwtUtils.getRoleFromToken(token);

            request.setAttribute("userId", userId);
            request.setAttribute("username", username);
            request.setAttribute("userRole", role);

            return true;

        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("{\"code\":401,\"message\":\"认证信息无效\"}");
            return false;
        }
    }

    /**
     * 判断是否为不需要认证的路径
     */
    private boolean isExcludedPath(String requestURI) {
        String[] excludedPaths = {
            "/users/register",
            "/users/login",
            "/users/logout",
            "/swagger-ui",
            "/v2/api-docs",
            "/swagger-resources",
            "/webjars",
            "/favicon.ico",
            "/error"
        };

        for (String excludedPath : excludedPaths) {
            if (requestURI.contains(excludedPath)) {
                return true;
            }
        }

        return false;
    }
}
